package com.peaker.advertisingpro.fragment

import android.graphics.Bitmap
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.peaker.advertisingpro.R
import com.peaker.advertisingpro.activity.ScrollActivity
import com.peaker.advertisingpro.adapter.ImageAdapter
import com.peaker.advertisingpro.adapter.MultipleTypesAdapter
import com.peaker.advertisingpro.bean.Interaction
import com.peaker.advertisingpro.bean.Scene
import com.peaker.advertisingpro.bean.Weather
import com.peaker.advertisingpro.entity.DataBean
import com.peaker.advertisingpro.entity.ViewSetObject
import com.peaker.advertisingpro.listener.OnPlayCompletionListener
import com.peaker.advertisingpro.utils.*
import com.peaker.advertisingpro.view.FullScreenDialog
import com.peaker.advertisingpro.view.WeatherView
import com.peaker.advertisingpro.viewholder.VideoHolder
import com.to.aboomy.pager2banner.Banner
import com.youth.banner.listener.OnPageChangeListener
import kotlinx.android.synthetic.main.fragment_scroll.*
import java.io.File


private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"


class ScrollFragment : Fragment() {

    private var sceneBean: Scene? = null
    private var param2: String? = null
    private var musicIndex: Int = 0

    //保存播放元素
    lateinit var banberMap: MutableMap<String, com.youth.banner.Banner<DataBean, MultipleTypesAdapter>>

    lateinit var mediaPlayer: MediaPlayer
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            sceneBean = it.getParcelable(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_scroll, container, false)
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: Scene, param2: String) =
            ScrollFragment().apply {
                arguments = Bundle().apply {
                    putParcelable(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)

                }
            }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //设置场景内容
        sceneBean?.css?.backgroundColor?.let {

            if (it.isNullOrEmpty().not()) {
                fragment_rootview.setBackgroundColor(Color.parseColor(it))
                LogToFile.d(
                    "图片地址背景颜色: ",
                    it
                )
            }
        }

        if (sceneBean?.css?.backgroundImage.isNullOrEmpty().not()) {
            fragment_rootview.background = BitmapUtils.fileToDrawable(
                Common.DIRADDRESS + File.separator + param2 + sceneBean?.css?.backgroundImage,
                resources
            )
            LogToFile.d(
                "图片地址背景图片: ",
                Common.DIRADDRESS + File.separator + param2 + sceneBean?.css?.backgroundImage
            )
        }

        //播放音乐
        var nullOrEmpty = sceneBean?.css?.backgroundMusic.isNullOrEmpty()
        if (nullOrEmpty.not()) {
            setMusic()
        }


        //设置播放元素
        setPlayElement()
    }

    private fun setMusic() {
        sceneBean?.css?.backgroundMusic?.get(musicIndex)?.url?.let {
            if (it.isNullOrEmpty()) return
            mediaPlayer =
                SmdtManagerUtils.openAudioFun(Common.DIRADDRESS + File.separator + param2 + it)

        }
        mediaPlayer.setOnCompletionListener {
            musicIndex++

            sceneBean?.css?.backgroundMusic?.get(musicIndex)?.url?.let {
                SmdtManagerUtils.openAudioFun(Common.DIRADDRESS + File.separator + param2 + it)
            }
        }
    }

    /**
     * 设置播放元素
     */
    private fun setPlayElement() {
        sceneBean?.elements?.forEach { it ->
            when (it.type) {
                0 -> {//文字
                    val viewSetObject = ViewSetObject(context!!, fragment_rootview)
                    viewSetObject.height = it.css?.height!!
                    viewSetObject.width = it.css!!.width!!
                    viewSetObject.topMargin = it.css?.top!!
                    viewSetObject.leftMargin = it.css?.left!!
                    viewSetObject.path = it.property?.content!!
                    viewSetObject.textFont = it.property?.fontFamily
                    viewSetObject.textSize = it.property?.fontSize!!.toFloat()
                    it.property?.color?.let {
                        viewSetObject.textColor = Color.parseColor(Utils.fixColor(it))
                    }
                    viewSetObject.textAlign = it.property?.textAlign
                    it.property?.backgroundColor?.let {

                        viewSetObject.backGroudColor = Color.parseColor(Utils.fixColor(it))
                    }
                    viewSetObject.direction = it.property?.mod!!
                    viewSetObject.fontStyle = it.property?.fontStyle!!
                    viewSetObject.fontWeight = it.property?.fontWeight!!
                    viewSetObject.textDecoration = it.property?.textDecoration!!
                    //跳转场景
                    viewSetObject.funtion = {
                        setAction(it.Interaction!!)
                    }

                    NewShowViewUtils.newTextView(viewSetObject)

                }
                1 -> {//图片  相当于就是轮播图
                    var banner = Banner(context)
                    fragment_rootview.layoutParams
                    val layoutParams = RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT
                    )
                    layoutParams.width = it.css!!.width!!
                    layoutParams.height = it.css!!.height!!
                    layoutParams.leftMargin = it.css!!.left!!
                    layoutParams.topMargin = it.css!!.top!!
                    banner.elevation = it.css?.zIndex!!.toFloat()
                    banner.layoutParams = layoutParams
                    fragment_rootview.addView(banner)
                    var list = ArrayList<Bitmap>()
                    it.property?.res?.let { res ->
                        res.forEach { re ->
                            list.add(BitmapUtils.fileToBitmap(Common.DIRADDRESS + File.separator + param2 + re.url))
                            LogToFile.d(
                                "图片地址: ",
                                Common.DIRADDRESS + File.separator + param2 + re.url
                            )
                        }
                    }
                    banner.adapter = ImageAdapter(list)
                    banner.isAutoPlay = true
//                    banner.setAutoTurningTime(TimeUtil.getLongMs(5))
                    it.property?.resConfigs?.duration?.let {
                        banner.setAutoTurningTime(TimeUtil.getLongMs(it))
                    }
                    banner.setOuterPageChangeListener(object : ViewPager2.OnPageChangeCallback() {

                    })
                    banner.setIndicator(null)
                    banner.viewPager2.isUserInputEnabled = false
                    banner.startTurning()

                    banner.setOnClickListener { view ->
                        setAction(it.Interaction!!)

                    }

                }
                2 -> { // 视屏轮播图
                    val layoutParams = RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT
                    )
                    layoutParams.width = it.css!!.width!!
                    layoutParams.height = it.css!!.height!!
                    layoutParams.leftMargin = it.css!!.left!!
                    layoutParams.topMargin = it.css!!.top!!
                    var banner = com.youth.banner.Banner<DataBean, MultipleTypesAdapter>(context)
                    banner.layoutParams = layoutParams
                    fragment_rootview.addView(banner)
                    var dataList = ArrayList<DataBean>()
                    it.property?.res?.forEach {
                        dataList.add(
                            DataBean(
                                Common.DIRADDRESS + File.separator + param2 + it.url,
                                "",
                                2
                            )
                        )
                    }
                    var multipleTypesAdapter = MultipleTypesAdapter(context, dataList)
                    //播放完成 监听
                    multipleTypesAdapter.setOnPlayCompletionListener(object :
                        OnPlayCompletionListener {
                        override fun OnCompletion(position: Int, type: Int) {
                            val count = banner.itemCount
                            val next = (banner.currentItem + 1) % count
                            banner.currentItem = next
                        }

                    })
                    banner.addBannerLifecycleObserver(this)
                        .setAdapter(multipleTypesAdapter)
                        .isAutoLoop(false)
                        .setUserInputEnabled(false)
//                        .setLoopTime(TimeUtil.getLongMs(10))
//                        .setLoopTime(10_000)
                        .start()
                    banner.addOnPageChangeListener(object : OnPageChangeListener {
                        override fun onPageScrollStateChanged(state: Int) {

                        }

                        override fun onPageScrolled(
                            position: Int,
                            positionOffset: Float,
                            positionOffsetPixels: Int
                        ) {

                        }

                        override fun onPageSelected(position: Int) {
                            if (multipleTypesAdapter.getItemViewType(position) != 2) return
                            multipleTypesAdapter.vhMap.get(position)?.let {
                                var player = (it as VideoHolder).player
                                // player.stopPlayback()
                                if (player.isPlaying.not()) {
                                    player.start()

                                }

                            }

                        }

                    })
                    banner.currentItem = banner.currentItem
                    banner.setOnBannerListener { data, position ->

                        setAction(it.Interaction!!)
                    }
                }

                3 -> {//文档  轮播图
                    var banner = Banner(context)
                    fragment_rootview.layoutParams
                    val layoutParams = RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT
                    )
                    layoutParams.width = it.css!!.width!!
                    layoutParams.height = it.css!!.height!!
                    layoutParams.leftMargin = it.css!!.left!!
                    layoutParams.topMargin = it.css!!.top!!
                    banner.elevation = it.css?.zIndex!!.toFloat()
                    banner.layoutParams = layoutParams
                    banner.viewPager2.isUserInputEnabled = false
                    fragment_rootview.addView(banner)
                    var list = ArrayList<Bitmap>()

                    it.property?.res?.let { res ->
                        res.forEach { re ->
                            var pdfToBitmap = pdfUtils.pdfToBitmap(
                                File(Common.DIRADDRESS + File.separator + param2 + re.url),
                                resources
                            )
                            pdfToBitmap?.let {
                                list.addAll(pdfToBitmap)
                            }
                        }
                    }
                    banner.adapter = ImageAdapter(list)
                    banner.isAutoPlay = true
                    banner.setAutoTurningTime(TimeUtil.getLongMs(it.property?.res?.first()?.duration!!))
                    banner.setIndicator(null)
                    banner.startTurning()

                    banner.setOnClickListener { view ->
                        setAction(it.Interaction!!)
                    }
                }
                4 -> {//混播
                    val layoutParams = RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT
                    )
                    layoutParams.width = it.css!!.width!!
                    layoutParams.height = it.css!!.height!!
                    layoutParams.leftMargin = it.css!!.left!!
                    layoutParams.topMargin = it.css!!.top!!

                    var banner = com.youth.banner.Banner<DataBean, MultipleTypesAdapter>(context)
                    banner.layoutParams = layoutParams
                    fragment_rootview.addView(banner)
                    var list = ArrayList<DataBean>()
                    it.property?.res?.let {
                        it.forEach { res ->
                            if (res.type == "1") {
                                list.add(
                                    DataBean(
                                        Common.DIRADDRESS + File.separator + param2 + res.url,
                                        "",
                                        1
                                    )
                                )

                            } else {
                                list.add(
                                    DataBean(
                                        Common.DIRADDRESS + File.separator + param2 + res.url,
                                        "",
                                        2
                                    )
                                )
                            }
                        }
                    }
                    var multipleTypesAdapter = MultipleTypesAdapter(context, list)
                    multipleTypesAdapter.setOnPlayCompletionListener(object :OnPlayCompletionListener{
                        override fun OnCompletion(position: Int, type: Int) {
                            val count = banner.itemCount
                            val next = (banner.currentItem + 1) % count
                            if(type==2){
                            banner.currentItem = next
                            }else{

                            }
                        }

                    })
                    banner.addBannerLifecycleObserver(this)
                        .setAdapter(multipleTypesAdapter)
                        .isAutoLoop(true)
                        .setUserInputEnabled(false)
                        .setLoopTime(TimeUtil.getLongMs(it.property?.res?.first()?.duration!!))
                        .start()

                    banner.addOnPageChangeListener(object : OnPageChangeListener {
                        override fun onPageScrollStateChanged(state: Int) {}

                        override fun onPageScrolled(
                            position: Int,
                            positionOffset: Float,
                            positionOffsetPixels: Int
                        ) {
                        }

                        override fun onPageSelected(position: Int) {


                            banner.setLoopTime(TimeUtil.getLongMs(it.property?.res?.get(position)?.duration!!))
                        }

                    })

                    banner.setOnBannerListener { data, position ->
                        setAction(it.Interaction!!)
                    }


                }
                5 -> {//天气
                    var weatherView = WeatherView(context!!, fragment_rootview)
                    weatherView.setView(
                        it.css?.width!!,
                        it.css?.height!!,
                        it.css?.left!!,
                        it.css?.top!!,
                        it.css?.zIndex!!.toFloat()
                    )
                    val type = object : TypeToken<Weather>() {}.type
                    val data = Gson().fromJson<Weather>(Common.json, type)
                    weatherView.setWeatherData(data)
                    weatherView.startHttp()
                    weatherView.startHttpWeather()
                    weatherView.getView().setOnClickListener { view ->
                        setAction(it.Interaction!!)
                    }

                }
                6 -> { //时间
                    val viewSetObject = ViewSetObject(context!!, fragment_rootview)
                    viewSetObject.height = it.css?.height!!
                    viewSetObject.width = it.css!!.width!!
                    viewSetObject.topMargin = it.css?.top!!
                    viewSetObject.leftMargin = it.css?.left!!
                    viewSetObject.path = it.property?.format!!
                    viewSetObject.textFont = it.property?.fontFamily
                    viewSetObject.textSize = it.property?.fontSize!!.toFloat()
                    it.property?.color?.let {
                        viewSetObject.textColor = Color.parseColor(it)
                    }
                    viewSetObject.textAlign = it.property?.textAlign
                    it.property?.backgroundColor?.let {
                        if (it.isNullOrEmpty().not()) {
                            viewSetObject.backGroudColor = Color.parseColor(it)
                        }
                    }
                    //跳转场景
                    viewSetObject.funtion = {
                        setAction(it.Interaction!!)
                    }
                    NewShowViewUtils.newTimeView(viewSetObject)

                }
                7 -> {//网页
                    val viewSetObject = ViewSetObject(context!!, fragment_rootview)
                    viewSetObject.height = it.css?.height!!
                    viewSetObject.width = it.css!!.width!!
                    viewSetObject.topMargin = it.css?.top!!
                    viewSetObject.leftMargin = it.css?.left!!
                    viewSetObject.path = it.property?.url!!
                    viewSetObject.zIndex = it.css?.zIndex!!
                    viewSetObject.time = TimeUtil.getLongMs(it.property?.refreshTime!!)
                    viewSetObject.funtion = {
                        setAction(it.Interaction!!)
                    }
                    NewShowViewUtils.newWebView(viewSetObject)

                }
                8 -> {//直播流  相当于是视屏轮播
                    val layoutParams = RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT
                    )
                    layoutParams.width = it.css!!.width!!
                    layoutParams.height = it.css!!.height!!
                    layoutParams.leftMargin = it.css!!.left!!
                    layoutParams.topMargin = it.css!!.top!!
                    var banner = com.youth.banner.Banner<DataBean, MultipleTypesAdapter>(context)
                    banner.layoutParams = layoutParams
                    fragment_rootview.addView(banner)
                    var dataList = ArrayList<DataBean>()
                    it.property?.res?.forEach {
                        dataList.add(
                            DataBean(
                                Common.DIRADDRESS + File.separator + param2 + it.url,
                                "",
                                2
                            )
                        )
                    }
                    var multipleTypesAdapter = MultipleTypesAdapter(context, dataList)
                    banner.addBannerLifecycleObserver(this)
                        .setAdapter(multipleTypesAdapter)
                        .isAutoLoop(true)
                        .setUserInputEnabled(false)
                        .setLoopTime(TimeUtil.getLongMs(it.property?.res?.first()?.duration!!))
                        .start()

                    banner.addOnPageChangeListener(object : OnPageChangeListener {
                        override fun onPageScrollStateChanged(state: Int) {}

                        override fun onPageScrolled(
                            position: Int,
                            positionOffset: Float,
                            positionOffsetPixels: Int
                        ) {
                        }

                        override fun onPageSelected(position: Int) {
                            if (multipleTypesAdapter.getItemViewType(position) != 2) return
                            multipleTypesAdapter.vhMap.get(position)?.let {
                                var player = (it as VideoHolder).player
                                if (player.isPlaying.not()) {
                                    player.start()
                                }
                            }
                            banner.setLoopTime(TimeUtil.getLongMs(it.property?.res?.get(position)?.duration!!))
                        }

                    })
                    banner.setOnBannerListener { data, position ->

                        setAction(it.Interaction!!)
                    }

                }
                9 -> {//按钮
                    val viewSetObject = ViewSetObject(context!!, fragment_rootview)
                    viewSetObject.height = it.css?.height!!
                    viewSetObject.width = it.css!!.width!!
                    viewSetObject.topMargin = it.css?.top!!
                    viewSetObject.leftMargin = it.css?.left!!
                    viewSetObject.path = it.property?.content!!
                    viewSetObject.textFont = it.property?.fontFamily
                    viewSetObject.textSize = it.property?.fontSize!!.toFloat()
                    it.property?.color?.let {
                        viewSetObject.textColor = Color.parseColor(Utils.fixColor(it))
                    }
                    it.property?.backgroundColor?.let {
                        viewSetObject.backGroudColor = Color.parseColor(Utils.fixColor(it))
                    }
                    viewSetObject.zIndex = it.css?.zIndex!!
                    viewSetObject.textAlign = it.property?.textAlign
                    viewSetObject.funtion = {
                        setAction(it.Interaction!!)
                    }
                    NewShowViewUtils.newBtnView(viewSetObject)

                }

                10 -> {//HDMI


                }
                11 -> {//动态元素
                    if (this::banberMap.isInitialized.not()) {
                        banberMap = mutableMapOf()
                    }
                    val layoutParams = RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT
                    )
                    layoutParams.width = it.css!!.width!!
                    layoutParams.height = it.css!!.height!!
                    layoutParams.leftMargin = it.css!!.left!!
                    layoutParams.topMargin = it.css!!.top!!
                    var banner = com.youth.banner.Banner<DataBean, MultipleTypesAdapter>(context)
                    banner.layoutParams = layoutParams
                    fragment_rootview.addView(banner)
                    banberMap[it.id!!] = banner
                    var list = ArrayList<DataBean>()
                    it.property?.res?.let {
                        it.forEach { res ->
                            if (res.type == "1") {
                                list.add(
                                    DataBean(
                                        Common.DIRADDRESS + File.separator + param2 + res.url,
                                        "",
                                        1
                                    )
                                )

                            } else {
                                list.add(
                                    DataBean(
                                        Common.DIRADDRESS + File.separator + param2 + res.url,
                                        "",
                                        2
                                    )
                                )
                            }
                        }
                    }
                    var multipleTypesAdapter = MultipleTypesAdapter(context, list)
                    multipleTypesAdapter.setOnPlayCompletionListener(object :OnPlayCompletionListener{
                        override fun OnCompletion(position: Int, type: Int) {
                            val count = banner.itemCount
                            val next = (banner.currentItem + 1) % count
                            if(type==2){
                                banner.currentItem = next
                            }else{
                                Utils.postDelayed(it.property?.res?.get(position)?.duration!!) {
                                    banner.currentItem = next
                                }
                            }
                        }

                    })
                    banner.addBannerLifecycleObserver(this)
                        .setAdapter(multipleTypesAdapter)
                        .isAutoLoop(false)
                        .setUserInputEnabled(false)
//                        .setLoopTime(TimeUtil.getLongMs(it.property?.res?.first()?.duration!!))
                        .start()

                    banner.addOnPageChangeListener(object : OnPageChangeListener {
                        override fun onPageScrollStateChanged(state: Int) {

                        }

                        override fun onPageScrolled(
                            position: Int,
                            positionOffset: Float,
                            positionOffsetPixels: Int
                        ) {

                        }

                        override fun onPageSelected(position: Int) {
                            if (multipleTypesAdapter.getItemViewType(position) != 2) return
                            multipleTypesAdapter.vhMap.get(position)?.let {
                                var player = (it as VideoHolder).player
                                if (player.isPlaying.not()) {
                                    player.start()
                                }
                            }
                          //  banner.setLoopTime(TimeUtil.getLongMs(it.property?.res?.get(position)?.duration!!))
                        }

                    })

                }
            }

        }
    }

    /**
     * 跳转动态元素
     */
    fun jumpElement(resId: String, id: String) {

        sceneBean?.elements?.forEach {
            if (it.id == resId) {
                banberMap[resId]?.currentItem = id.toInt()
            }
        }


    }

    override fun onDestroy() {
        super.onDestroy()
//        Log.d("frament$param2","onDestroy")
    }


    override fun onResume() {
        super.onResume()
        Log.d("frament$param2", "onResume")
    }

    override fun onStop() {
        super.onStop()
//        Log.d("frament$param2","onStop")
    }

    /**
     * 设置点击事件
     */
    fun setAction(data: Interaction) {
        //0-无交互 1-跳转到场景  2-第三方网站 3-动态元素  4-全屏预览 5-apk跳转
        when (data.type) {
            0 -> return
            1 -> {
                (activity as ScrollActivity).jumpScenes(data.linkSeceneId!!)
            }
            2 -> {
                val dialog = FullScreenDialog(context!!, data.linkUrl!!)
                dialog.show()
            }
            3 -> {
                (activity as ScrollActivity).jumpScenesE(data.linkSeceneId!!, data.linkDynamic!!)
            }
            4 -> {//全屏预览

            }
            5 -> {
                (activity as ScrollActivity).jumpApp(data.linkApk!!)
            }


        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
    }
}